/**
 * atwork远程接口访问工具类, 用于统一定义远程接口访问服务
 */


var request = require('request');
var config = require('../conf/config');
var util = require('util');

module.exports = function(){

    var exec = function(url, callback) {
        if (config.currEvn == 'test') {
            oauthToken(function(token){
                url = url.indexOf('?') != -1 ? (url + '&access_token=' + token) : (url + '?access_token=' + token);
                callback(url);
            });
        } else {
            callback(url);
        }
    };

    // 获取鉴权token
    var oauthToken =  function(callback){
        request({
            method: 'GET',
            uri: config.remote[config.currEvn].url + '/api/oauth/token?grant_type=client_credentials&client_id=' + global.client_id + '&client_secret=' + global.client_secret,
            encoding: 'utf-8'
        }, function(error, response, body) {
            try {
                console.info('从@work鉴权反回内容为：%s', JSON.stringify(body));
                var token = JSON.parse(body).access_token;
            } catch (e) {
                console.error('后台返回的内容不是json格式');
                return;
            }
            !callback || callback(token);
        });
    };

    /**
     * 消息发送
     * @param params
     * {
     *  msgBody:  [{ 'description': msg,
     *              'picUrl': 'http://112.124.102.52:8000/img/push-title-img.jpg',
     *              'title': '你有新任务',
     *              'url': 'http://112.124.102.52:8000/#detail/{{username}}/' + _id
     *           }],
     *  users:[userId],
     *  callback : function
     */
    var sendMsg =   function(params){
        var url = config.remote[config.currEvn].url + '/api/service/msg/send';
        exec(url, function(url){
            request({
                method: 'POST',
                uri: url,
                json: true,
                encoding: 'utf-8',
                headers: { 'Content-type': 'application/json' },
                body: JSON.stringify({
                    "chatType": "ServiceNum",
                    "contentType": "News",
                    "from": {
                        "type": "ServiceNum",
                        "value": config.appkey
                    },
                    "to": {
                        "type": "User",
                        "value": params.users
                    },
                    "news": {
                        "articleCount": params.msgBody.length,
                        "articles": params.msgBody
                    }
                })

            }, function(err, response, body) {
                console.info('消息发送接口返回状态%s，返回内容%s', response.statusCode, JSON.stringify(body));
                if (params.callback) {
                    params.callback(err, body);
                }
            })
        });
    };

    // 首次登录进行登录验证
    var validUserToken = function(params, callback){
        var user = params.user;
        var userToken = params.token;
        var url = util.format('%s/api/service/auth/validUserToken/%s/%s',config.remote[config.currEvn].url, user, userToken);

        exec(url, function(_url){
            request({
                method: 'GET',
                uri: _url,
                encoding: "utf-8"
            }, function(error, _response, body){
                console.info('登录验证返回内容为：%s', JSON.stringify(body));
                var status = _response.statusCode;
                var data = JSON.parse(body);
                var isSucceed = (status == 200 && !error && !data.errcode && data.status.toLowerCase() == 'ok');
                var command = {
                    400 : 'Token无效或请求非法',
                    401 : 'Token过期',
                    403 : '验证参数错误',
                    200 : util.format('用户%s鉴权验证%s!', user, (isSucceed ? '成功' : '失败'))
                };

                console.info(command[status]);
                !callback || callback(isSucceed, data);
            });
        });
    };

    var getHeadImg = function(req, res){
        var url = config.remote[config.currEvn].url + '/api/service/contact/avatar/download?' + decodeURI(req.params.url);

        exec(url, function(_url){
            request.get(_url).pipe(res);
        });
    };

    return {
        oauthToken  :   oauthToken,
        sendMsg :   sendMsg,
        getHeadImg : getHeadImg,
        validUserToken    : validUserToken
    };
}();